<template>
  <div class="page-container">
    <div class="page-header">
      <h2 class="page-title">订单管理</h2>
      <el-button @click="refreshOrders" :loading="loading">
        <el-icon><Refresh /></el-icon>
        刷新
      </el-button>
    </div>

    <!-- 订单状态筛选 -->
    <el-card class="mb-3">
      <el-tabs v-model="activeStatus" @tab-change="handleStatusChange">
        <el-tab-pane label="全部" name=""></el-tab-pane>
        <el-tab-pane label="待确认" name="PAID"></el-tab-pane>
        <el-tab-pane label="制作中" name="PREPARING"></el-tab-pane>
        <el-tab-pane label="待配送" name="READY"></el-tab-pane>
        <el-tab-pane label="配送中" name="DELIVERING"></el-tab-pane>
        <el-tab-pane label="已完成" name="COMPLETED"></el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 订单列表 -->
    <div class="orders-container">
      <el-card v-for="order in orders" :key="order.id" class="order-card mb-3">
        <!-- 订单头部 -->
        <div class="order-header">
          <div class="order-info">
            <span class="order-number">订单号：{{ order.orderNumber }}</span>
            <span class="order-time">{{ formatTime(order.createTime) }}</span>
          </div>
          <el-tag :type="getStatusType(order.status)" size="large">
            {{ getStatusText(order.status) }}
          </el-tag>
        </div>

        <!-- 客户信息 -->
        <div class="customer-info">
          <el-icon><User /></el-icon>
          <span class="customer-name">{{ order.deliveryName }}</span>
          <span class="customer-phone">{{ order.deliveryPhone }}</span>
        </div>

        <!-- 订单商品 -->
        <div class="order-items">
          <div v-for="item in order.items" :key="item.id" class="order-item">
            <div class="item-info">
              <img v-if="item.image" :src="item.image" :alt="item.itemName" class="item-image" />
              <div v-else class="item-icon"><el-icon><Food /></el-icon></div>
              <div class="item-details">
                <div class="item-name">{{ item.itemName }}</div>
                <div v-if="item.remark" class="item-spec">备注：{{ item.remark }}</div>
              </div>
            </div>
            <div class="item-price">
              <div class="price">¥{{ item.unitPrice }}</div>
              <div class="quantity">x{{ item.quantity }}</div>
            </div>
          </div>
        </div>

        <!-- 配送信息 -->
        <div class="delivery-info" v-if="order.deliveryAddress">
          <el-icon><Location /></el-icon>
          <span>{{ order.deliveryAddress }}</span>
        </div>

        <!-- 订单金额 -->
        <div class="order-amount">
          <div class="amount-total">
            <span>实付金额：</span>
            <span class="total-price">¥{{ order.finalAmount }}</span>
          </div>
        </div>

        <!-- 订单操作 -->
        <div class="order-actions">
          <el-button 
            v-if="order.status === 'PAID'" 
            type="success" 
            size="small"
            @click="confirmOrder(order)"
          >
            确认订单
          </el-button>
          <el-button 
            v-if="order.status === 'PAID'" 
            type="danger" 
            size="small"
            @click="rejectOrder(order)"
          >
            拒绝订单
          </el-button>
          <el-button 
            v-if="order.status === 'PREPARING'" 
            type="primary" 
            size="small"
            @click="markReady(order)"
          >
            制作完成
          </el-button>
          <el-button size="small" @click="viewOrderDetail(order)">
            查看详情
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>

    <!-- 空状态 -->
    <el-empty v-if="!loading && orders.length === 0" description="暂无订单" />

    <!-- 分页 -->
    <div v-if="total > 0" class="pagination-wrapper">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 订单详情弹窗 -->
    <el-dialog v-model="detailVisible" title="订单详情" width="600px">
      <div v-if="selectedOrder" class="order-detail">
        <div class="detail-section">
          <h4>订单信息</h4>
          <div class="detail-item">
            <span class="label">订单号：</span>
            <span>{{ selectedOrder.orderNumber }}</span>
          </div>
          <div class="detail-item">
            <span class="label">下单时间：</span>
            <span>{{ formatTime(selectedOrder.createTime) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">订单状态：</span>
            <el-tag :type="getStatusType(selectedOrder.status)">
              {{ getStatusText(selectedOrder.status) }}
            </el-tag>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 拒绝订单弹窗 -->
    <el-dialog v-model="rejectVisible" title="拒绝订单" width="400px">
      <el-form :model="rejectForm" label-width="80px">
        <el-form-item label="拒绝原因">
          <el-select v-model="rejectForm.reason" placeholder="请选择拒绝原因">
            <el-option label="商品已售完" value="商品已售完" />
            <el-option label="超出配送范围" value="超出配送范围" />
            <el-option label="店铺休息" value="店铺休息" />
            <el-option label="其他原因" value="其他原因" />
          </el-select>
        </el-form-item>
        <el-form-item label="详细说明">
          <el-input
            v-model="rejectForm.detail"
            type="textarea"
            :rows="3"
            placeholder="请输入详细说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rejectVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmReject" :loading="rejecting">确认拒绝</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, User, Food, Location } from '@element-plus/icons-vue'
import { getMerchantOrders, updateOrderStatus } from '../../api/order'
import dayjs from 'dayjs'

// 响应式数据
const loading = ref(false)
const orders = ref([])
const activeStatus = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const detailVisible = ref(false)
const selectedOrder = ref(null)
const rejectVisible = ref(false)
const rejecting = ref(false)
const rejectForm = ref({ reason: '', detail: '' })

// 获取订单列表
const getOrders = async () => {
  try {
    loading.value = true
    const params = {
      page: currentPage.value - 1,
      size: pageSize.value,
      status: activeStatus.value || undefined
    }
    
    const response = await getMerchantOrders(params)
    
    if (response.success) {
      orders.value = response.data.content || []
      total.value = response.data.totalElements || 0
    } else {
      ElMessage.error(response.message || '获取订单列表失败')
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 刷新订单
const refreshOrders = () => {
  currentPage.value = 1
  getOrders()
}

// 状态变更处理
const handleStatusChange = () => {
  currentPage.value = 1
  getOrders()
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  getOrders()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  getOrders()
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    'PENDING': 'warning',
    'PAID': 'info',
    'PREPARING': 'primary',
    'READY': 'success',
    'DELIVERING': 'primary',
    'COMPLETED': 'success',
    'CANCELLED': 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    'PENDING': '待支付',
    'PAID': '待确认',
    'PREPARING': '制作中',
    'READY': '待配送',
    'DELIVERING': '配送中',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  }
  return textMap[status] || '未知状态'
}

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

// 确认订单
const confirmOrder = async (order) => {
  try {
    await ElMessageBox.confirm('确认接受此订单？', '确认订单', {
      confirmButtonText: '确认接受',
      cancelButtonText: '取消',
      type: 'success'
    })
    
    await updateOrderStatus(order.id, 'PREPARING')
    ElMessage.success('订单已确认，请尽快制作')
    refreshOrders()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('确认订单失败')
    }
  }
}

// 拒绝订单
const rejectOrder = (order) => {
  selectedOrder.value = order
  rejectForm.value = { reason: '', detail: '' }
  rejectVisible.value = true
}

// 确认拒绝
const confirmReject = async () => {
  if (!rejectForm.value.reason) {
    ElMessage.warning('请选择拒绝原因')
    return
  }
  
  try {
    rejecting.value = true
    const reason = rejectForm.value.detail ? 
      `${rejectForm.value.reason}：${rejectForm.value.detail}` : 
      rejectForm.value.reason
    
    await updateOrderStatus(selectedOrder.value.id, 'CANCELLED', reason)
    ElMessage.success('订单已拒绝')
    rejectVisible.value = false
    refreshOrders()
  } catch (error) {
    ElMessage.error('拒绝订单失败')
  } finally {
    rejecting.value = false
  }
}

// 标记制作完成
const markReady = async (order) => {
  try {
    await ElMessageBox.confirm('确认商品已制作完成？', '制作完成', {
      confirmButtonText: '确认完成',
      cancelButtonText: '取消',
      type: 'success'
    })
    
    await updateOrderStatus(order.id, 'READY')
    ElMessage.success('已标记为制作完成，等待配送员取餐')
    refreshOrders()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 查看订单详情
const viewOrderDetail = (order) => {
  selectedOrder.value = order
  detailVisible.value = true
}

// 页面初始化
onMounted(() => {
  getOrders()
})
</script>

<style scoped>
.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.orders-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.order-card {
  border: 1px solid var(--border-extra-light);
  border-radius: var(--border-radius-large);
  overflow: hidden;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: var(--bg-page);
  border-bottom: 1px solid var(--border-extra-light);
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.order-number {
  font-weight: 600;
  color: var(--text-primary);
}

.order-time {
  font-size: var(--font-size-small);
  color: var(--text-secondary);
}

.customer-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  border-bottom: 1px solid var(--border-extra-light);
}

.customer-name {
  font-weight: 500;
  color: var(--text-primary);
}

.customer-phone {
  color: var(--text-secondary);
  margin-left: auto;
}

.order-items {
  padding: 16px 20px;
}

.order-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.order-item:last-child {
  margin-bottom: 0;
}

.item-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.item-image {
  width: 48px;
  height: 48px;
  border-radius: var(--border-radius-base);
  object-fit: cover;
}

.item-icon {
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--bg-page);
  border-radius: var(--border-radius-base);
  color: var(--text-secondary);
}

.item-details {
  flex: 1;
}

.item-name {
  font-weight: 500;
  color: var(--text-primary);
  margin-bottom: 4px;
}

.item-spec {
  font-size: var(--font-size-small);
  color: var(--text-secondary);
}

.item-price {
  text-align: right;
}

.price {
  font-weight: 600;
  color: var(--primary-color);
  margin-bottom: 4px;
}

.quantity {
  font-size: var(--font-size-small);
  color: var(--text-secondary);
}

.delivery-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  background: var(--bg-page);
  border-top: 1px solid var(--border-extra-light);
  font-size: var(--font-size-small);
  color: var(--text-regular);
}

.order-amount {
  padding: 16px 20px;
  border-top: 1px solid var(--border-extra-light);
}

.amount-total {
  display: flex;
  justify-content: space-between;
  font-weight: 600;
}

.total-price {
  color: var(--primary-color);
  font-size: var(--font-size-medium);
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding: 16px 20px;
  border-top: 1px solid var(--border-extra-light);
  background: var(--bg-page);
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

.order-detail {
  max-height: 500px;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  margin: 0 0 12px 0;
  font-size: var(--font-size-medium);
  color: var(--text-primary);
}

.detail-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: var(--font-size-small);
}

.detail-item .label {
  color: var(--text-regular);
  width: 80px;
  flex-shrink: 0;
}

@media (max-width: 768px) {
  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .order-actions {
    flex-wrap: wrap;
  }
  
  .item-info {
    gap: 8px;
  }
  
  .item-image,
  .item-icon {
    width: 40px;
    height: 40px;
  }
}
</style>
